package xuegao.study.mall.file.service;

import com.alibaba.fastjson.JSONObject;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import xuegao.study.mall.file.config.MinioProperties;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.InputStream;

@Component
public class MinioService {
    private Logger logger = LoggerFactory.getLogger(MinioService.class);

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties properties;

    public boolean upload(File file) {
        String filename = file.getName();
        try {
            minioClient.uploadObject(UploadObjectArgs.builder()
                    .bucket(properties.getBucket())
                    .object(filename)
                    .filename(file.getAbsolutePath())
                    .build());
            return true;
        } catch (Exception e) {
            logger.error("file upload minio exception, file name: {}", filename, e);
            return false;
        }
    }

    public JSONObject upload(MultipartFile file) {
        return upload(file, null, null);
    }

    public JSONObject upload(MultipartFile file, String fileName) {
        return upload(file, fileName, null);
    }

    public JSONObject upload(MultipartFile file, String fileName, String path) {
        String uploadFileName = file.getOriginalFilename();
        if (!StringUtils.isEmpty(fileName)) {
            uploadFileName = fileName;
        }
        if (!StringUtils.isEmpty(path)) {
            uploadFileName = path + uploadFileName;
        }
        try {
            InputStream inputStream = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(properties.getBucket())
                    .object(uploadFileName)
                    .stream(inputStream, inputStream.available(), -1)
                    .contentType(file.getContentType())
                    .build());
            JSONObject result = new JSONObject();
            result.put("name", fileName);
            result.put("url", properties.getEndpoint() + "/" + properties.getBucket() + "/" + fileName);
            return result;
        } catch (Exception e) {
            logger.error("file upload minio exception, file name: {}", uploadFileName, e);
            throw new RuntimeException();
        }
    }
}
